//引入食物类
import Food from './food'
//引入蛇类
import Snake from './Snake'
// 引入分数类
import ScorePancel from './ScorePancel'
class ContralClass {
    // 食物
    food: Food;
    // 蛇
    snake: Snake;
    //分数面板
    scorePancel: ScorePancel;
    // 蛇移动的方向
    direction: string = '';
    // 蛇是否活着，即蛇是否继续移动
    isLive: Boolean = true;
    constructor() {
        this.food = new Food();
        this.snake = new Snake();
        this.scorePancel = new ScorePancel(10, 2);

        // 初始化事件
        this.init();
    }
    init() {
        // 键盘事件
        document.addEventListener('keydown', this.keydownHandle.bind(this))
        // 让蛇移动
        this.run();
    }
    // 键盘事件处理
    keydownHandle(e: KeyboardEvent) {
        this.direction = e.key;
    }
    run() {
        let X = this.snake.X;
        let Y = this.snake.Y;
        switch (this.direction) {
            // 向左移动
            case 'ArrowLeft':
            case 'Left':
                X -= 10;
                break;
            // 向右移动
            case 'ArrowRight':
            case 'Right':
                X += 10;
                break;
            //向上移动
            case 'ArrowUp':
            case 'Up':
                Y -= 10;
                break;
            //向下移动
            case 'ArrowDown':
            case 'Down':
                Y += 10;
                break;
        }
        // 检测是否吃到食物
        this.checkEatFood(X, Y);
        try {
            console.log(this.scorePancel.level);
            this.snake.X = X;
            this.snake.Y = Y;
        } catch (e) {
            alert(e.message + 'GAME OVER')
            this.isLive = false;
        }


        this.isLive && setTimeout(() => {
            this.run();
        }, 300 - 30 * this.scorePancel.level)
    }
    checkEatFood(X: number, Y: number) {
        if (this.food.X === X && this.food.Y === Y) {
            console.log('吃到了食物');
            this.scorePancel.addScore();
            this.food.changeFoodPostion();
            this.snake.addBodys();
        }
    }


}
export default ContralClass;